import React, { ButtonHTMLAttributes, HTMLProps, ReactNode } from 'react';

import cn from 'classnames';
import Link, { LinkProps } from 'next/link';

import cs from './Button.module.scss';

export enum ButtonVariants {
  Main = 'main',
  Secondary = 'secondary',
  Danger = 'danger',
  Login = 'login',
  Primary = 'primary',
  Gray = 'gray',
  Blue = 'blue',
  Link = 'link',
  LinkGray = 'link_gray',
  LinkDanger = 'link_danger',
  Icon = 'icon',
  Logout = 'logout',
  Green = 'green',
}

interface Props {
  variant?: ButtonVariants;
  className?: string;
  link?: boolean;
  noHover?: boolean;
}
interface ButtonProps extends Props, ButtonHTMLAttributes<HTMLButtonElement> {
  link?: false;
}

interface ButtonAsLinkProps extends Props, LinkProps, Omit<HTMLProps<HTMLAnchorElement>, 'as' | 'ref'> {
  href: string;
  link?: true;
  children: ReactNode;
}

export const Button = ({
  link = false,
  variant,
  className,
  noHover,
  children,
  ...props
}: ButtonAsLinkProps | ButtonProps) => {
  const getClassName = React.useMemo(
    () => (variant?: ButtonVariants, className?: string) =>
      cn(cs.button, variant && cs[variant], className, noHover && cs.no_hover),
    [cs.button, cs, noHover],
  );

  if (link) {
    const { href, ...rest } = props as ButtonAsLinkProps;
    return (
      <Link className={getClassName(variant, className)} href={href} target="_self" {...rest}>
        {children}
      </Link>
    );
  }
  const { onClick, ...rest } = props as ButtonProps;
  return (
    <button className={getClassName(variant, className)} onClick={(e) => onClick?.(e)} type="button" {...rest}>
      {children}
    </button>
  );
};
